package com.tanhua.api.impl.mongo;

import com.tanhua.api.db.SoulLockApi;
import com.tanhua.domain.mongo.SoulLock;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @author Richard Wang
 * @date 2021/9/5 18:25
 */
@Service
public class SoulLockApiImpl implements SoulLockApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public SoulLock checkLockState(Long userId) {
        //1.查询soulLock表(mongoDb)中是否有该用户对三种问题卷的标记
        Query query = new Query(Criteria.where("userId").is(userId.intValue()));
        SoulLock soulLock = mongoTemplate.findOne(query, SoulLock.class);
        //2.若无,即当前用户属于第一次答题,则设定初始值为0,1,1(基础题解锁,中级及高级题均锁定)
        if (soulLock == null) {
            soulLock = new SoulLock();
            soulLock.setUserId(userId.intValue());
            soulLock.setBase(0);
            soulLock.setMiddle(1);
            soulLock.setHigh(1);
            mongoTemplate.insert(soulLock);
        }
        //3.若有,表示该用户之前答过题,直接返回
        return soulLock;
    }

    @Override
    public void switchOnNextPage(Long userId, Integer paperId) {
        Query query = new Query(Criteria.where("userId").is(userId.intValue()));
        Update update = new Update();
        switch (paperId) {
            //若当前提交的是基础卷,则将中级卷设置为解锁
            case 1:
                update.set("middle", 0);
                mongoTemplate.upsert(query, update, SoulLock.class);
                break;
            //若当前提交的是中级卷,则将高卷设置为解锁
            case 2:
                update.set("high", 0);
                mongoTemplate.upsert(query, update, SoulLock.class);
                break;
        }
    }
}
